In [6]:
# 'generic import' of math module
import math
math.sqrt(25)
Out[6]:
In [7]:
# import a function
from math import sqrt
sqrt(25) # no longer have to reference the module
Out[7]:
In [8]:
# import multiple functions at once
from math import cos, floor
# import all functions in a module (generally discouraged)
from csv import *
# define an alias
import datetime as dt
Determine type of an object
In [9]:
print(type(2)) #int
In [10]:
type(2.0) #float
Out[10]:
In [11]:
type("two") #string
Out[11]:
In [12]:
type(True) # bool
Out[12]:
In [13]:
type(None) #NoneType
Out[13]:
Check if an object is of a given type
In [14]:
isinstance(2.0, float)
Out[14]:
In [15]:
isinstance("two", (float, str))
Out[15]:
Convert an object to a given type
In [16]:
float(2)
Out[16]:
In [17]:
int(2.9)
Out[17]:
In [18]:
str(2.9)
Out[18]:
Zero, None and empty containers are converted to False:
In [19]:
bool(0)
Out[19]:
In [20]:
bool(None)
Out[20]:
In [21]:
bool('') # empty string
Out[21]:
In [22]:
bool({}) # empty dictionary
Out[22]:
Non-Empty containers and non-zeros are converted to True
In [23]:
bool(2)
Out[23]:
In [24]:
bool('two')
Out[24]:
In [25]:
bool([2])
Out[25]:
In [26]:
bool({'key':'val'})
Out[26]:
In [27]:
10 ** 4 # exponent
Out[27]:
In [28]:
5 % 4 # modulo
Out[28]:
In [29]:
# previous versions of python did integer division
# python 3 coerces values into floats
10/4
Out[29]:
In [30]:
10 // 4 # floor division
Out[30]:
In [31]:
x = 5
In [32]:
x != 3
Out[32]:
In [33]:
x >= 5 and x < 10
Out[33]:
In [34]:
x < 5 or x ==5
Out[34]:
In [35]:
if x > 0:
print('positive')
elif x == 0:
print('zero')
else:
print('negative')
In [36]:
#single-line if
if x > 0: print('positive')
In [37]:
#single line if/else statement (ternary operator)
'positive' if x > 0 else 'zero or negative'
Out[37]:
range returns a sequence of integers from 0 to n-1
In [38]:
# includes the start value but not the stop value [start, end)
range(0,3) #[0, ,1, 2]
rng = range(0,3)
list(rng)
Out[38]:
In [39]:
# default start is 0
rng = range(3)
list(rng)
Out[39]:
In [40]:
#third argument is a step value
rng = range(0,5,2)
list(rng)
Out[40]:
for loops:
In [41]:
# not the recommended style
fruits = ['apple', 'banana', 'cherry']
for i in range(len(fruits)):
print(fruits[i].upper())
In [42]:
# recommended style
for fruit in fruits:
print(fruit.upper())
In [43]:
# iterate through two things at once (using tuple unpacking)
family = {'dad':'homer', 'mom':'marge', 'size':6}
for key, value in family.items():
print( key,value)
In [44]:
# use enumerate if you need to access the index value within the loop
for index,fruit in enumerate(fruits):
print(index,fruit)
for/else loop:
In [45]:
for fruit in fruits:
if fruit == 'banana':
print('Found the banana!')
break # exit the loop and skip the 'else' block
else:
# this block executes ONLY if the for loop completes without hitting 'break'
print("Can't find the banana")
while loop:
In [46]:
count = 0
while count < 5:
print('printing %s time(s)' % count)
count += 1
In [ ]:
weekdays = ['mon', 'tues', 'wed', 'thurs', 'fri']
In [ ]:
weekdays[0]
In [ ]:
# elements 0 (inclusive) to 3 (exclusive)
weekdays[0:3]
In [ ]:
# starting point implied to be zero
weekdays[:3]
In [ ]:
# elements 3 (inclusive) through implied end
weekdays[3:]
In [ ]:
# last element
weekdays[-1]
In [ ]:
# eveery second element (step by 2)
weekdays[::2]
In [ ]:
# backwards (step by -1)
weekdays[::-1]
In [ ]:
In [1]:
# the With statement (like using in C#) is used to issue cleanup code when a variable comes out of scope
class cleanup_thing:
def __enter__(self):
self.open=True
return self
def __exit__(self, type, value, traceback):
self.open=False
def isOpen(self):
return self.open
with cleanup_thing() as thing:
print(thing.isOpen())
print(thing.isOpen())
In [ ]:
from datetime import datetime
from datetime import timedelta
#get now
datetime.today()
In [ ]:
a = datetime(2012, 9, 23)
a
In [ ]:
b = timedelta(days=2, hours=6)
a+b
In [ ]:
a-b
In [ ]:
d=b+timedelta(hours=4.5)
d.days
In [ ]:
d.seconds
In [ ]:
# total timedelta in seconds
d.total_seconds()
Converting to / from strings
In [ ]:
text = '2012-09-20'
datetime.strptime(text, '%Y-%m-%d')
In [ ]:
z = datetime(2012, 9, 23, 21, 37, 4, 177393)
datetime.strftime(z, '%A %B %d, %Y')
Time Zones
In [ ]:
from pytz import timezone
d = datetime(2012, 12, 21, 9, 30, 0)
# localize the date for Chicago
central = timezone('US/Central')
loc_d = central.localize(d)
print(loc_d)
In [ ]:
# Convert to Bangalore time
bang_d = loc_d.astimezone(timezone('Asia/Kolkata'))
print(bang_d)